import axios from 'axios';

const hosts = {
  development: '',
  test: '//xld.babytree-test.com',
  production: '//xld.babytree.com',
};

// 创建一个axios实例
const instance = axios.create({
  // withCredentials: true // 设置允许携带cookie
});

function isLoginTimeOut(data) {
  if (data.status === 9999) {
    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);
  }
}

const isEmpty = (value: any) =>
  value === undefined || value === null || value === '';

const cleanParams = (params?: Record<string, any>) => {
  if (params && Object.keys(params).length > 0) {
    return Object.fromEntries(
      Object.entries(params).filter(
        ([key, value]) => !isEmpty(value) && !isEmpty(key)
      )
    );
  }
};

// 发送请求的函数
export function post(url: string, data?: any) {
  const host = hosts[process.env.REACT_APP_ENV];
  const params = new URLSearchParams(); // 创建对象
  if (data instanceof Object) {
    Object.keys(data).forEach((item) => {
      if (!isEmpty(data[item])) {
        params.append(`${item}`, `${data[item]}`);
      }
    });
  }
  // 发送请求
  return instance({
    method: 'post',
    url: `${host}${url}`,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    data: params,
  })
    .then((response: any) => {
      isLoginTimeOut(response.data);
      return Promise.resolve(response);
    })
    .catch((error: any) => {
      return Promise.reject(error);
    });
}

// 保存接口使用form-data
export function postForm(url: string, data?: any) {
  const host = hosts[process.env.REACT_APP_ENV];
  // 发送请求
  return instance({
    method: 'post',
    url: `${host}${url}`,
    headers: {
      'Content-Type': 'application/json',
    },
    data,
  })
    .then((response: any) => {
      isLoginTimeOut(response.data);
      return Promise.resolve(response);
    })
    .catch((error: any) => {
      return Promise.reject(error);
    });
}

export function upload(
  url: string,
  data: FormData,
  progress?: (progressEvent: any) => void
) {
  const host = hosts[process.env.REACT_APP_ENV];
  // 发送请求
  return instance({
    method: 'post',
    url: `${host}${url}`,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    data,
    onUploadProgress: progress,
  })
    .then((response: any) => {
      isLoginTimeOut(response.data);
      return Promise.resolve(response);
    })
    .catch((error: any) => {
      return Promise.reject(error);
    });
}
